package com.kz.himalaya.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import java.io.IOException;

public class PlayService extends Service {
    private MediaPlayer player;

    public PlayService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
            player = new MediaPlayer();
            player.setLooping(true);
            player.setOnPreparedListener(new MyPrepareListener());
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
//        throw new UnsupportedOperationException("Not yet implemented");
        return new MyBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    public void loadMusic(String musicUrl) {
        if (player != null) {
            if (player.isPlaying()) {
                player.stop();
            }
            player.reset();
            try {
                player.setDataSource(musicUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
            player.prepareAsync();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stop();
    }

    //暂停播放
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
        } else {
            if (player != null && !player.isPlaying()) {
                player.start();
            }
        }
    }

    //开始播放
    private void start() {
        if (!player.isPlaying()) {
            player.start();
        }
    }

    //停止播放
    private void stop() {
        if (player != null) {
            player.release();
            player = null;
        }
    }

    //指定位置播放
    private void seekToPorgress(int percent) {
        if (player != null && player.isPlaying()) {
            int duration = player.getDuration();
//            duratio
//            player.seekTo(progress);
        }
    }
    //获取播放时间
    private int getCurrtTime(){
        if (player!=null && player.isPlaying()) {
            return player.getDuration();
        }
        return 0;
    }
    public class MyBinder extends Binder {
        public PlayService getService() {
            return PlayService.this;
        }
    }

    //音乐播放准备监听
    private class MyPrepareListener implements MediaPlayer.OnPreparedListener {

        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    }
    private class MyCompletionListener implements MediaPlayer.OnCompletionListener{

        @Override
        public void onCompletion(MediaPlayer mp) {

        }
    }
}
